import React,{useState,useEffect, useMemo} from "react";
import './WrjSubaccount.less'
import {Button,Table, Dropdown,Modal,Select,Input,message } from 'antd';
import {ClearOutlined} from '@ant-design/icons';
import type { MenuProps} from 'antd';
import {EllipsisOutlined} from '@ant-design/icons';
import SubaccountAdd from "../subaccountAdd/SubaccountAdd";
import SubaccountEdit from "../SubaccountEdit/SubaccountEdit";
import moment from 'moment';
import request from "../../../utils/axios";
import { useSelector } from "react-redux";


interface StandingType{
    _id:string,
    name:string,
    description:string,
    newTime:string
}
interface DataType {
    key:React.Key,
    _id:string;
    username: string;
    password: string;
    mobile: string;
    newTime: string;
    loginTime: string;
    standing:any;
    status:boolean,
    level:number
}

const Subaccount: React.FC =()=>{
    const standingName=useSelector((store:any)=>store.counter.standingName)
    const { TextArea } = Input;

    const [isModalOpenAdd, setIsModalOpenAdd] = useState(false);
    const [isModalOpenDelete,setIsModalOpenDelete]=useState(false)
    const [isModalOpenEdit,setIsModalOpenEdit]=useState(false)
    const [isModalOpenEnable,setIsModalOpenEnable]=useState(false)
    const [isModalOpenService,setIsModalOpenService]=useState(false)
    const [enableMsg,setEnableMsg]=useState('')
    const [serviceMsg,setServiceMsg]=useState('')

    const [deleteId,setDeleteId]=useState('')
    const [editItem,setEditItem]=useState({})

    const [editStatusItem,setEditStatusItem]=useState<any>({})


    const [subaccount,setSubaccount]=useState('')
    const [standing,setStanding]=useState('')
    const [status,setStatus]=useState('')
    const [standingList,setStandingList]=useState<StandingType[]>([])
    const [userList,setUserList]=useState([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [loading, setLoading] = useState(false);

    const [serviceLength,setServiceLength]=useState('')

    //账号停用原因
    const options=[
        {
            value:'该账号违规操作',
            label:'该账号违规操作'
        },
        {
            value:'账号活动异常',
            label:'账号活动异常'
        },
        {
            value:'长期不活跃',
            label:'长期不活跃'
        },
    ]

    //使用状态
    const statusOptions=[
        { value: ' ', label: '全部' },
        { value: true, label: '使用中' },
        { value: false, label: '已停用' }
    ]
    
    //获取身份
    const getstanding=async()=>{
        request.get("getstanding").then(error=>{
            console.log(error);
        }).catch(response=>{
            setStandingList(response.data.standingList)
        })
    }

    //获取子账号
    const getuser=async()=>{
        request.get("getuser",{username:subaccount,standing:standing,status:status}).then(error=>{
            console.log(error);
        }).catch(response=>{
            setUserList(response.data.userList)
        })
    }
      
    // 表格标题
    const columns: any= [
        { title: '编号', dataIndex: 'index' ,key:'_id'},
        { title: '账号', dataIndex: 'username' ,key:'username'},
        { title: '身份', dataIndex: 'standing' ,key:'standing'},
        { title: '最后登录时间', dataIndex: 'loginTime' ,key:'loginTime'},
        { title: '创建时间', dataIndex: 'newTime' ,key:'newTime',
            sorter: (a: DataType, b: DataType) => moment(a.newTime, 'YYYY-MM-DD HH:mm:ss').unix() - moment(b.newTime, 'YYYY-MM-DD HH:mm:ss').unix(),
            sortDirections: ['descend', 'ascend'],
        },
        { title: '使用状态', dataIndex: 'status' ,key:'status'},
        { title: '操作', dataIndex: 'caozuo' ,key:'caozuo'}
    ];

    // 返回新数组
    const newUserList = useMemo(() => {
        let list:any=[]
        userList.forEach((item:DataType)=>{
            if(item.level==2){
                list.push(item)
            }
        })
        return list
    }, [userList]);
    
    // 操作
    const items: MenuProps['items'] = [
        {
          key: '1',
          label: '修改子账号信息'
        },
        {
          key: '2',
          label: '停用/启用子账号'
        },
        {
          key: '3',
          label: '删除子账号'
        },
    ];
    
    //数据渲染
    const dataSource:any = newUserList.map((item:DataType,index:number) => {
        if(item.level==2){
            return {
                key:item._id,
                index:index+1,
                username:[
                    <div>
                        <p>admin:{item.username}</p>
                        <p style={{color:'gray',fontSize:'12px'}}>+86{item.mobile}</p>
                    </div>
                ],
                standing:item.standing[0].name,
                loginTime:item.loginTime.split('T')[0]+' '+item.loginTime.split('T')[1].split('.')[0],
                newTime:item.newTime.split('T')[0]+' '+item.newTime.split('T')[1].split('.')[0],
                status:item.status?'使用中':'已停用',
                caozuo: standingName=='超级管理员' || standingName=='管理员' ?
                [
                    <Dropdown menu={{items,onClick: (e) => {
                        if(e.key=='1'){
                            setIsModalOpenEdit(true)
                            setEditItem(item)
                        }else if(e.key=='2'){
                            setEditStatusItem(item)
                            if(item.status==false){
                                setEnableMsg('确定要启用该账号吗？')
                                setIsModalOpenEnable(true)
                            }else{
                                setServiceMsg('确定要停用该账号吗？')
                                setIsModalOpenService(true)
                            }
                        }else if(e.key=='3'){
                            delSubaccount(item._id)                                
                        }
                    }}} trigger={['click']} placement="bottom">
                        <EllipsisOutlined />
                    </Dropdown>
            ]: null
            }
        }
    });

    // 多选
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection: any = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    //添加成功，取消模态框
    const handleCancelAdd=(data:boolean)=>{
        setIsModalOpenAdd(data)
        getuser()
    }
    //编辑成功，取消模态框
    const handleCancelEdit=(data:boolean)=>{
        setIsModalOpenEdit(data)
        getuser()
    }

    //删除出现确认框
    const delSubaccount=async(id:any)=>{
        setDeleteId(id)
        setIsModalOpenDelete(true)
    }
    //确认删除
    const handleOkDelete=async()=>{
        try {
            await request.deleteParam(`deluser/${deleteId}`);
            getuser();
            setIsModalOpenDelete(false);
        } catch (error) {
            console.error('DELETE (param) error:', error);
        }
    }

    //停用
    const handleOkService=async()=>{
        if(selectedRowKeys.length==0){
            try {
                await request.put(`editusermore/${editStatusItem._id}`,{status:false});
                getuser()
                setIsModalOpenService(false)
                setSelectedRowKeys([])
            } catch (error) {
                console.error(error);
            }
        }else{
            try {
                await request.put(`editusermore/${selectedRowKeys}`,{status:false});
                getuser()
                setIsModalOpenService(false)
                setSelectedRowKeys([])
            } catch (error) {
                console.error(error);
            }
        }
    }

    //启用
    const handleOkEnable=async()=>{
        if(selectedRowKeys.length==0){
            try {
                await request.put(`editusermore/${editStatusItem._id}`,{status:true});
                getuser()
                setIsModalOpenEnable(false)
                setSelectedRowKeys([])
            } catch (error) {
                console.error(error);
            }
        }else{
            try {
                await request.put(`editusermore/${selectedRowKeys}`,{status:true});
                getuser()
                setIsModalOpenEnable(false)
                setSelectedRowKeys([])
            } catch (error) {
                console.error(error);
            }
        }
    }

    const clear=()=>{
        setSubaccount('')
        setStanding('')
        setStatus('')
        // getuser()
    }

    useEffect(()=>{
        getstanding()
        getuser()
    },[])

    return (
        <div className="wrj-subaccount-box">
            <div className="wrj-subaccount-search">
                <div className="wrj-subaccount-search-input">
                    <span>子账号：</span>
                    <input type="text" placeholder="请输入子账号" value={subaccount} onChange={(e)=>{setSubaccount(e.target.value)}}/>
                </div>
                <div className="wrj-subaccount-search-input">
                    <span>身份：</span>
                    <select onChange={(e)=>{setStanding(e.target.value)}} value={standing} style={{width:'80%'}}>
                        <option value=''>全部</option>
                        {
                            standingList.map(item=>{
                                return <option key={item._id} value={item._id}>{item.name}</option>
                            })
                        }
                    </select>
                </div>
                <div className="wrj-subaccount-search-input">
                    <span>使用状态：</span>
                    <select onChange={(e)=>{setStatus(e.target.value)}} value={status}>
                        {
                            statusOptions.map((item:any,index)=>{
                                return <option key={index} value={item.value}>{item.label}</option>
                            })
                        }
                    </select>
                </div>
                <Button shape="round" size='middle' className="wrj-subaccount-search-button" onClick={()=>{getuser()}}>搜索</Button>
                <p style={{marginTop:'-20px',color:'gray',marginLeft:'20px',cursor:"pointer"}} onClick={clear}><ClearOutlined style={{marginRight:'3px'}}/>清除条件</p>
            </div>
            {
                standingName=='超级管理员' || standingName=='管理员'?
                <div style={{marginTop:'10px',marginBottom:'20px'}}>
                <Button type='primary' onClick={()=>{setIsModalOpenAdd(true)}} shape="round" size='middle' style={{color:'#fff',marginRight:'20px'}} className="wrj-subaccount-search-button">+添加子账号({newUserList.length}/20)</Button>
                <Button shape="round" size='middle' style={{marginRight:'20px'}} className="wrj-subaccount-search-button" onClick={()=>{
                    if(selectedRowKeys.length==0){
                        message.info('请选择要停用的账号');
                    }else{
                        setIsModalOpenService(true),
                        setServiceMsg(`确定要停用这${selectedRowKeys.length}个账号吗？`)
                    }
                }}>批量停用</Button>
                <Button shape="round" size='middle' style={{marginRight:'20px'}} className="wrj-subaccount-search-button" onClick={()=>{
                    if(selectedRowKeys.length==0){
                        message.info('请选择要启用的账号');
                    }else{
                        setIsModalOpenEnable(true),
                        setEnableMsg(`确定要启用这${selectedRowKeys.length}个账号吗？`)
                    }
                }}>批量启用</Button>
            </div>:null
            }
            <Table rowSelection={rowSelection} columns={columns} dataSource={dataSource} />
            {/* 添加 */}
            {
                isModalOpenAdd?
                <SubaccountAdd isModalOpenAdd={isModalOpenAdd} handleCancelAdd={handleCancelAdd}></SubaccountAdd>:
                <div></div>
            }
            {/* 编辑 */}
            {
                isModalOpenEdit?
                <SubaccountEdit isModalOpenEdit={isModalOpenEdit} handleCancelEdit={handleCancelEdit} editItem={editItem}></SubaccountEdit>:
                <div></div>
            }
            {/* 确认删除框 */}
            <Modal title="确定要删除该账号吗？" open={isModalOpenDelete} onOk={handleOkDelete} onCancel={()=>{setIsModalOpenDelete(false)}} okText='确定' cancelText='取消'>
                <p>子账号被删除后将无法恢复，请慎重操作！</p>
            </Modal>

            {/* 停用 */}
            <Modal title={serviceMsg} open={isModalOpenService} onOk={handleOkService} onCancel={()=>{setIsModalOpenService(false)}} okText='确定' cancelText='取消'>
                <p>子账号被停用后将恢复登录配送调度系统，请慎重操作!</p>
                <div className="wrj-service-box">
                    <label>禁用原因：</label>
                    <Select defaultValue="请选择原因" options={options} style={{ width: '60%' }}/>
                </div>
                <div className="wrj-service-box1">
                    <label>补充说明：</label>
                    <TextArea rows={4} style={{width:'60%'}} value={serviceLength} onChange={(e:any)=>{
                        if(serviceLength.length==200){
                            setServiceLength(e.target.value.substring(0, 20));
                            message.info('最多输入可200个字')
                        }else{
                            setServiceLength(e.target.value);
                        }
                    }} placeholder='请输入补充说明'/>
                    <span style={{color:'gray',fontSize:'12px',marginLeft:'10px'}}>{serviceLength.length}/200(选填)</span>
                </div>
            </Modal>

            {/* 启用 */}
            <Modal title={enableMsg} open={isModalOpenEnable} onOk={handleOkEnable} onCancel={()=>{setIsModalOpenEnable(false)}} okText='确定' cancelText='取消'>
                <p>子账号被启用后将恢复登录配送调度系统，请慎重操作!</p>
            </Modal>
        </div>
    )
}

export default Subaccount